//----------------------------------------------------------------------------
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
/**
 * 将小程序的API封装成支持Promise的API
 * @params fn {Function} 小程序原始API，如wx.login
 */
function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }

      obj.fail = function (res) {
        reject(res)
      }

      fn(obj)
    })
  }
}
//----------------------------------------------------------------------------
/*
    发送模板消息：程序块
 */
function sendTemplate(sendData) {
  wx.cloud.callFunction({
    name: 'sendMessage',
    data: {
      postData: sendData
    }
  })
    .then(res => {
      console.log(res)
      if (res.errMsg == 'cloud.callFunction:ok') {
        //云函数执行完毕
        if (res.result.errmsg == 'ok') //向用户发送模板消息成功
        {
          console.log('已通知用户：订单状态变更')
        } else {
          console.log('本次状态变更无法发送模板消息:preypayId次数用尽')
        }
      } else {
        console.log('本次状态变更无法发送模板消息:云函数执行错误')
      }
    })
    .catch(err => {
      console.log('本次状态变更无法发送模板消息:云函数执行错误')
    })
}
//--------------------------------------判断当前时间是否在规定时间内

var timeRange = function (beginTime, endTime) {
  var strb = beginTime.split(":");
  if (strb.length != 2) {
    return false;
  }
  var stre = endTime.split(":");
  if (stre.length != 2) {
    return false;
  }
  var b = new Date();
  var e = new Date();
  var n = new Date();

  b.setHours(strb[0]);
  b.setMinutes(strb[1]);
  e.setHours(stre[0]);
  e.setMinutes(stre[1]);

  if (n.getTime() - b.getTime() > 0 && n.getTime() - e.getTime() < 0) {
    return true;
  } else {
    return false;
  }
}
var queryShopSettings = function () {
  return  wx.cloud.database().collection('settings').doc('W6H8EO9Ghf6stBZy').get()
}
//----------------------------------------------------------------------------
/*
    添加会员卡
 */

function openVipCard(template_card_id) {

  let signStr = '' //签名
  wx.cloud.callFunction({
    name: 'addVipCard',
    data: {
      card_id: template_card_id
    }
  })
    .then(res => {
      if (res.result) //判断执行登录的云函数是否正确返回
      {
        let paras = res.result
        console.log(paras)
        let temp = {
          timestamp: Number(paras.timestamp),
          nonce_str: paras.nonce_str,
          signature: paras.signature
        }
        signStr = JSON.stringify(temp)
        console.log(signStr)
      }
    }).then(res => {
      wx.addCard({
        cardList: [{
          //会员卡ID
          cardId: template_card_id,
          cardExt: signStr
        }],
        success: res => {
          console.log(res.cardList) // 卡券添加结果
          console.log('打开会员卡成功') // 卡券添加结果
        }
      })
    })
}
//----------------------------------------------------------------------------
/*
    打开会员卡界面
 */
function openVipCardByCode(template_cardid, code) {
  wx.openCard({
    cardList: [{
      cardId: template_cardid,
      code: code
    }],
    success(res) {
      wx.hideLoading()
    }
  })
}
/*
    登录程序备份
 */
function login_code() {
  //---------------------------1.检查登录
  if (getApp().globalData.login == false) {
    this.loginFormShow(true);
    return;
  }
  //---------------------------2.用户如果登录过，说明肯定授权过，但是仍需要检测用户信息授权状态
  var js_code = ''
  var session_key = ''
  var encryptedData = ''
  var iv = ''
  wx.pro.getSetting().then(res => {
    console.log(res.authSetting)
    //如果用户自行关闭了信息授权，需要弹出设置
    if (res.authSetting['scope.userInfo'] === false || res.authSetting === null) {
      wx.showModal({
        title: '友情提示',
        content: '请首先进入设置中打开[用户信息]授权后再次尝试',
        showCancel: false,
      })
    }
    return;
  }).then(res => { //确保[用户信息授权]后，通过login+getUserInfo获取信息传至云开发解密unionid  
    return new Promise((resolve, reject) => {
      wx.pro.login().then(res => { //login获取code
        console.log(res)
        js_code = res.code
      }).then(res => { //code传至云端api发送http请求获取session_key登录态
        console.log(js_code)
        wx.cloud.callFunction({
          name: 'getSessionKey',
          data: {
            js_code
          }
        }).then(res => { //通过getUserInfo获取加密数据
          console.log('session_key', JSON.parse(res.result).session_key)
          session_key = JSON.parse(res.result).session_key
          wx.pro.getUserInfo({
            withCredentials: true
          }).then(res => {
            console.log('encryptedData:', res.encryptedData)
            console.log('iv:', res.iv)
            encryptedData = res.encryptedData
            iv = res.iv
          }).then(res => {
            console.log({
              js_code,
              session_key,
              encryptedData,
              iv
            })
            wx.cloud.callFunction({
              name: 'getUnionid',
              data: {
                session_key,
                encryptedData,
                iv
              }
            }).then(res => {
              console.log(res)
            })
          })
        })
      })
    })
  })
}

//----------------------------------------------------------------------------
/*
    执行云函数[releaseOrder]:下发订单指令
 */
//----------------------------------------------------------------------------
function releaseOrderByOrderId(orderId){
   return wx.cloud.callFunction({
     name:'releaseOrder',
     data: {
       orderId: orderId
     }
  })
}
//----------------------------------------------------------------------------
/*
    执行云函数[deleteTempOrder]:删除临时订单
 */
//----------------------------------------------------------------------------
function deleteTempOrderByOrderId(orderId) {
  return wx.cloud.callFunction({
    name: 'deleteTempOrder',
    data: {
      orderId: orderId
    }
  })
}

module.exports = {
  formatTime: formatTime,
  wxPromisify: wxPromisify,
  sendTemplate: sendTemplate,
  timeRange: timeRange,
  queryShopSettings: queryShopSettings,
  openVipCard: openVipCard,
  openVipCardByCode: openVipCardByCode,
  releaseOrderByOrderId: releaseOrderByOrderId,
  deleteTempOrderByOrderId: deleteTempOrderByOrderId
}
